import React, { useState, useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { Button, Table, Modal, message, Tooltip } from 'antd';
import EditChannelModal from './Components/EditChannelModal'
import ImportChannelModal from './Components/ImportChannelModal'
import api from '../../api/activityManage'
import tool from '../../utils/commonFuc'

const ChannelList = (props) => {
    
    const [state, setState] = useState({
        searchData: {
            page: 1,
            rows: 10
        },
        channelList:[],//列表数据
        channelListTotal:0,//列表总数
        editModal:{//编辑数据
            visible: false,
            title:'新建渠道',
            data:{}
        },
        importModal:false,//导入模态框
    });

    //更新state
    const updateState = (newState) => {
        let data = JSON.parse(JSON.stringify(state))
        setState(Object.assign({}, data, newState))
    }
    useEffect(()=>{
        let actId = tool.getQueryString(props.location.search,'actId')//活动ID
        if(actId){
            state.searchData.actId = actId
        }
        getList()
    },[])
    const columns = [
        { title: '渠道名称', dataIndex: 'name', key: 'name', width: 80, },
        { title: '渠道类型', dataIndex: 'type', key: 'type', render: (text, record) => (
                <span>{record.type==1?'员工':''}</span>
            ),
        },
        { title: '员工工号', dataIndex: 'code', key: 'code', },
        { title: '渠道专属链接', dataIndex: 'url', key: 'url'/* , render: (text, record) => (
            <a href={record.url} target="_blank">{record.url}</a>
        ), */
    },
        { title: '渠道拉新数', dataIndex: 'cardCount', key: 'cardCount', },
        { title: '状态', dataIndex: 'state', key: 'state', render: (text, record) => (
                <span>{record.state==1?'有效':'无效'}</span>
            ),
        },
        {
            title: '操作', dataIndex: 'lll', key: 'lll', render: (text, record) => (
                <div>
                    <Button type="link" onClick={()=>{goToPage(record)}}>查看用户列表</Button>
                    <Button type="link" onClick={()=>{updateStatus(record)}}>更改状态</Button>
                </div>
            ),
        },        
    ];
    const pageObj = {// 表格分页对象
        size: "small",
        total: state.channelListTotal,
        pageSize: state.searchData.rows,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: () => `共 ${state.channelListTotal} 条`,
        onChange: (page) => {
            getList({page:page})
        },
        onShowSizeChange: (page, rows) => {
            getList({page:1,rows:rows})
        }
    }
    // 获取列表
    const getList = (data)=>{
        let obj = {
            actId:state.searchData.actId,
            page:data?(data.page?data.page:state.searchData.page):state.searchData.page,
            rows:data?(data.rows?data.rows:state.searchData.rows):state.searchData.rows,
        }
        obj = Object.assign({},obj,data?data:{})
        api.getChannelDataList(obj,(res)=>{
            console.log(res)
            updateState({
                searchData:obj,
                channelList:res.recordList,
                channelListTotal:res.totalCount
            })
        })
    }
    //跳转
    const goToPage = (data)=>{
        props.history.push({
            pathname:'/activityManage/userList',
            search:`chanId=${data.id}`
        })
    }
    // 更改状态
    const updateStatus = (data) =>{
        let obj = {
            id:data.id,
            state:data.state==1?0:1
        }
        api.updateStateChannelData(obj,(res)=>{
            if(res){
                message.success('更改成功！')
                getList()
            }
        })
    }
    //添加和编辑
    const showModal = (type,data)=>{
        // type:1-添加；2-编辑；3-关闭；4-关闭并调获取列表
        console.log(type,data)
        if(type==4){
            api.getChannelDataList(state.searchData,(res)=>{
                updateState({
                    channelList:res.recordList,
                    channelListTotal:res.totalCount,
                    editModal:{
                        visible:type>2?false:true,
                        title:type==1?'新建渠道':'编辑渠道',
                        data:{}
                    },
                    importModal:false
                })
            })
        }else{
            updateState({
                editModal:{
                    visible:type>2?false:true,
                    title:type==1?'新建渠道':'编辑渠道',
                    data:data
                }
            })
        }
    }
    //导入模态框
    const showImportModal = (val)=>{
        updateState({
            importModal:val
        })
    }
    //导出列表
    const exportList = ()=>{
        Modal.confirm({
            title: '提示',
            content: '是否要导出分发渠道？',
            onOk:() => {
                api.exportChannelData({actId:state.searchData.actId},(res)=>{
                    let objectUrl = window.URL.createObjectURL(new Blob([res], {
                        type: "application/vnd.ms-excel"
                      }))
                      // 文件地址
                      const link = document.createElement('a');
                      link.download = '分发渠道'+tool.getNowFormatDate()+'.xls';
                      link.href = objectUrl;
                      link.click();
                  })
            },
        })     
    }
    const goBack = ()=>{
        props.history.goBack()
    }
    return (
        <div>
            <div style={{ marginBottom: 30, paddingTop: 20 }}>
                <div className="clearfix" >
                    <Button type="primary" onClick={goBack} style={{marginRight:20}}>返回</Button>
                    <Button type="primary" onClick={()=>{showModal(1,{})}} style={{marginRight:20}}>新建渠道</Button>
                    <Button type="primary" onClick={()=>{showImportModal(true)}} style={{marginRight:20}}>批量生成员工渠道</Button>
                    <Button type="primary" onClick={exportList}>导出渠道列表</Button>
                </div>
            </div>
            <Table
                columns={columns}
                dataSource={state.channelList}
                pagination={pageObj}
                rowKey="id"
            />
            {/* 编辑渠道模态框 */}
            <EditChannelModal editModal={state.editModal} showModal={showModal} actId={state.searchData.actId}></EditChannelModal>
            <ImportChannelModal actId={state.searchData.actId} showModal={showModal} importModal={state.importModal} showImportModal={showImportModal}></ImportChannelModal>
        </div>
    )
}

export default withRouter(ChannelList)